//
//  CertificatesVC.m
//  New_Runway
//
//  Created by mack on 2018/1/31.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "CertificatesVC.h"
#import "AddPictureCell.h"
#import "IamgeFactory.h"
#import "NRWCarPhotoManager.h"

@interface CertificatesVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (nonatomic, strong) UICollectionView *collectionview;
@property (nonatomic, strong) UILabel *lable;
@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, strong) UIImage *picture;

@property (nonatomic, assign) BOOL isFirst;

@end

@implementation CertificatesVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationBarView.hidden = YES;
    self.view.backgroundColor = UIColorHex(0xf5f5f5);
    [self.view addSubview:self.lable];
    [self creatCollectionView];
    self.isFirst = YES;

}

-(UILabel *)lable{
    if (!_lable) {
        _lable = [[UILabel alloc] init];
        _lable.textColor = MAIN_FONT_COLOR();
        _lable.font = [UIFont systemFontOfSize:11];
        _lable.frame = CGRectMake(15, 0, Screen_width - 30, 30);
        _lable.numberOfLines = 2;
        _lable.text = @"默认第一张为保单，点击图片可以设置行驶证、登记证、保单";
    }
    return _lable;
}
-(void)creatCollectionView{
    //创建一个layout布局类
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    //设置布局方向为垂直流布局
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //设置每个item的大小为100*100
    //    layout.itemSize = CGSizeMake(100, 80);
    layout.minimumLineSpacing      = 5;
    layout.minimumInteritemSpacing = 5;
    //    [layout setHeaderReferenceSize:CGSizeMake(Screen_width, self.view.frame.size.width * 3 / 5)];
    //创建collectionView 通过一个布局策略layout来创建
    _collectionview = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 30, Screen_width, Screen_height  - self.BotH - self.navH - 40) collectionViewLayout:layout];
    //代理设置
    _collectionview.backgroundColor = UIColorHex(0xf5f5f5);
    _collectionview.delegate=self;
    _collectionview.dataSource=self;
    //注册item类型 这里使用系统的类型
    [_collectionview registerNib:[UINib nibWithNibName:@"AddPictureCell" bundle:nil] forCellWithReuseIdentifier:@"AddPictureCell"];
    
    [self.view addSubview:_collectionview];
    
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return 3;
    
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *array = @[@"保单",@"登记证",@"行驶证"];
    
    AddPictureCell * cell  = [collectionView dequeueReusableCellWithReuseIdentifier:@"AddPictureCell" forIndexPath:indexPath];
    [cell configData:nil indexPath:indexPath];
    cell.delateBtn.hidden = NO;
    cell.mainTitle.text = array[indexPath.row];
    if (_isFirst == YES) {
        
        if (indexPath.row == 0) {
            [cell.mainImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",ImageApi,self.imageModel.insurance]] placeholderImage:[UIImage imageNamed:@"addPic"]];
            if ([self.imageModel.insurance isEqualToString:@""]) {
                cell.delateBtn.hidden = YES;
            }
        }else if (indexPath.row == 1){
            
            [cell.mainImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",ImageApi,self.imageModel.registration_license]] placeholderImage:[UIImage imageNamed:@"addPic"]];
            if ([self.imageModel.registration_license isEqualToString:@""]) {
                cell.delateBtn.hidden = YES;
            }
        }else if (indexPath.row == 2){
             [cell.mainImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",ImageApi,self.imageModel.vehicle_license]] placeholderImage:[UIImage imageNamed:@"addPic"]];
            
            if ([self.imageModel.vehicle_license isEqualToString:@""]) {
                cell.delateBtn.hidden = YES;
            }
        }
    }else{
        
        if (self.selectIndex == indexPath.row) {
            cell.mainImage.image = self.picture;
        }
        if (indexPath.row == 0) {
            cell.delateBtn.hidden = YES;
        }
        
    }
    

    
    
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return CGSizeMake((Screen_width - 50) / 3, (Screen_width - 40) / 3 - 40);
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView
                       layout:(UICollectionViewLayout *)collectionViewLayout
       insetForSectionAtIndex:(NSInteger)section

{
    return UIEdgeInsetsMake(10, 15, 0, 15);//分别为上、左、下、右
    
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    self.selectIndex = indexPath.row;
    
    
    [self editPeopleMessage];
}

-(void)editPeopleMessage{
    
    UIActionSheet *sheet;
    
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        sheet  = [[UIActionSheet alloc] initWithTitle:@"拍照时建议横屏拍摄" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册选择", nil];
    }
    else {
        sheet = [[UIActionSheet alloc] initWithTitle:@"拍照时建议横屏拍摄" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册选择", nil];
    }
    
    
    [sheet showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        switch (buttonIndex) {
                
            case 0: //相机
                [self choosePictureType:YES];
                
                break;
            case 1: //相册
                
                [self choosePictureType:NO];
                
                break;
            case 2:
                return;
                break;
        }
    }
    else {
        switch (buttonIndex) {
            case 0:
                [self choosePictureType:NO];
                
                break;
            case 1:
                return;
                break;
                
        }
    }
//    // 跳转到相机或相册页面
//    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
//    imagePickerController.delegate = self;
//    imagePickerController.allowsEditing = YES;
//    imagePickerController.sourceType = sourceType;
//
//    [self presentViewController:imagePickerController animated:YES completion:^{}];
    
    
    
}
-(void)choosePictureType:(BOOL)isCamre{
    kSelfWeak;
    if (isCamre == YES) {
        [[NRWCarPhotoManager shareInstance] presentPicker:PickerType_Camera photoCut:PhotoCutType_YES target:self callBackBlock:^(UIImage *image, BOOL isCancel) {
            if (image) {
                NSData *data = [UIImage compressImage:image maxFileSize:300];
                weakSelf.isFirst = NO;
                weakSelf.picture = image;
                [weakSelf.collectionview reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.selectIndex inSection:0]]];
                [weakSelf uploadCarImage:weakSelf.selectIndex Image:data];
            }
      
        }];
    }else{
        [[NRWCarPhotoManager shareInstance] presentPicker:PickerType_Photo photoCut:PhotoCutType_YES target:self callBackBlock:^(UIImage *image, BOOL isCancel) {
            if (image) {
                NSData *data = [UIImage compressImage:image maxFileSize:300];
                weakSelf.isFirst = NO;
                weakSelf.picture = image;
                [weakSelf.collectionview reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.selectIndex inSection:0]]];
                [weakSelf uploadCarImage:weakSelf.selectIndex Image:data];
            }
          
        }];
    }
    
}

//- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
//{
//    [picker dismissViewControllerAnimated:YES completion:^{}];
//
//    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
//    NSData *data = [UIImage reSizeImageData:image maxImageSize:375 maxSizeWithKB:1024];
//    _isFirst = NO;
//    self.picture = image;
//    [self uploadCarImage:self.selectIndex Image:data];
//    [self.collectionview reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.selectIndex inSection:0]]];
//
//
//}

-(void)uploadCarImage:(NSInteger)selected Image:(NSData *)image{
    NSDictionary *params;
    NSArray *keyArray = @[@"insurance",@"registration_license",@"vehicle_license"];
    params = @{
               @"carId":self.carID,
               @"imageKey":keyArray[selected],
               };
    NSString *url = [NSString stringWithFormat:@"%@%@",Api,uploadImageApi];
    [SVProgressHUD show];
    [YQNetworking uploadFileWithUrl:url params:params fileData:image type:@"jpg" name:@"uploadFile" mimeType:@"image/*" progressBlock:^(int64_t bytesWritten, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        if ([response[@"code"] isEqual:@1]) {
         
            [self.imageModel setValue:response[@"result"][@"pathUrl"] forKey:keyArray[selected]];
            [ShowMessage showHintMessage:@"上传成功" duration:2.0 withRemindId:remindSuccess];
        }else{
            [ShowMessage showHintMessage:response[@"msg"] duration:2.0 withRemindId:remindFail];

        }
        [SVProgressHUD dismiss];
    } failBlock:^(NSError *error) {
        [SVProgressHUD dismiss];
        [ShowMessage showHintMessage:@"上传失败，请检查网络是否流畅" duration:2.0 withRemindId:remindFail];

    }];
}
- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo{
    NSIndexPath *index = userInfo[@"index"];
    NSArray *keyArray = @[@"insurance",@"registration_license",@"vehicle_license"];
    if ([eventName isEqualToString:@"delate"]) {
        _isFirst = YES;
        [self.imageModel setValue:@"" forKey:keyArray[index.row]];
        [self.collectionview reloadData];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
